/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.persistence.repository.collection.jpa;

import java.util.*;

import org.metalframework.persistence.engine.*;

/**
 * Delegates all operations to the underlying collection keeping track of what has been added, updated or modified
 * to propagate changes to the JPA EntityManager.
 * 
 * @since 1.0
 */
public class ProxyJpaPersistentCollectionStrategy<T> extends AbstractJpaPersistentCollectionStrategy<T> {

	private static final long serialVersionUID = -6891675847650719567L;

	private Collection<T> jpaCollection;
	
	public ProxyJpaPersistentCollectionStrategy(Class<T> entityType,
	                                            JapaEngine japaEngine,
	                                            Collection<T> jpaCollection) {
		super(entityType, japaEngine);
		this.jpaCollection = jpaCollection;
	}

	@Override
	protected void doAdd(int index, T entity) {
		if (index < size()) {
			asList().add(index, entity);
		} else {
			jpaCollection.add(entity);
		}
	}

	@Override
	protected T doGet(int index) {
		return asList().get(index);
	}

	@Override
	protected T doSet(int index, T entity) {
		return asList().set(index, entity);
	}

	@Override
	protected T doRemove(int index) {
		return asList().remove(index);
	}

	@Override
	protected boolean doRemove(T entity) {
		return jpaCollection.remove(entity);
	}

	@Override
	protected boolean doContains(T entity) {
		return jpaCollection.contains(entity);
	}

	@Override
	protected int doSize() {
		return jpaCollection.size();
	}

	@Override
	protected void flushed() {
		// Do nothing
	}
	
	protected List<T> asList() {
		return (List<T>)jpaCollection;
	}
}
